import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

// 将所有未登录会话重定向到 /login
router.beforeEach(async(to, from, next) => {
  
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  // const hasToken = getToken()
  // 如果是登录页面，则清空user
  if (to.path === '/login') {
    //退出登录
    store.dispatch('systemUser/logout').then(res => {
      sessionStorage.removeItem('user')
      next()
    })
  } else {
    //判断是否登录
    var isLogin = false
    await store.dispatch('systemUser/judgeLogin').then(res => {
      isLogin = res
    })
    var user = null
    if (isLogin) {
      user = sessionStorage.getItem('user')
    }else{
      sessionStorage.removeItem('user')
    }
    // 如果不是登录页面，且user为空，则跳转到登陆页面
    if (!isLogin && !user && to.path !== '/login') {
      next({
        path: '/login'
      })
      NProgress.done()
    } else if(to.path === '/dashboard') {
      await store.dispatch('systemUser/getInfo')
      next()
      NProgress.done()
    }else  {
      next()
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
